package com.ellecity06.cwhiskymall.ui.search

import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.QuickAdapterHelper
import com.chad.library.adapter.base.loadState.LoadState
import com.chad.library.adapter.base.loadState.trailing.TrailingLoadStateAdapter
import com.ellecity06.common.adapter.CustomLoadMoreAdapter
import com.ellecity06.common.base.BaseMvvmActivity
import com.ellecity06.common.ktx.addGridDecoration
import com.ellecity06.common.ktx.addLinearDecoration
import com.ellecity06.common.ktx.launchActivity
import com.ellecity06.common.ktx.observeEvent
import com.ellecity06.common.ktx.statusBar
import com.ellecity06.common.widgets.dialog.showAlert
import com.ellecity06.cwhiskymall.adapter.SearchDiscoverAdapter
import com.ellecity06.cwhiskymall.adapter.SearchHistoryAdapter
import com.ellecity06.cwhiskymall.adapter.SearchHotAdapter
import com.ellecity06.cwhiskymall.adapter.SearchHotTopAdapter
import com.ellecity06.cwhiskymall.databinding.ActivitySearchBinding
import com.ellecity06.cwhiskymall.ui.search.result.SearchResultActivity
import com.ellecity06.cwhiskymall.ui.webview.WebHelper
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent

/**
 * @author ellecity06
 * @time 2024/11/1 17:09
 * @des
 */
class SearchActivity : BaseMvvmActivity<ActivitySearchBinding, SearchViewModel>(),
    View.OnClickListener, TrailingLoadStateAdapter.OnTrailingListener {

    private val historyAdapter: SearchHistoryAdapter by lazy { SearchHistoryAdapter() }
    private val discoverAdapter: SearchDiscoverAdapter by lazy { SearchDiscoverAdapter() }
    private val hotTopAdapter: SearchHotTopAdapter by lazy { SearchHotTopAdapter() }
    private val hotAdapter: SearchHotAdapter by lazy { SearchHotAdapter() }
    private val keyword: String by lazy { intent.getStringExtra("keyword") ?: "" }


    override val userBaseTitle: Boolean
        get() = false

    override fun inflateBinding(): ActivitySearchBinding {
        return ActivitySearchBinding.inflate(layoutInflater)
    }

    override fun initialize(savedInstanceState: Bundle?) {
        statusBar(binding.statusBar)
        initView()
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(SearchIntent.FetchHistory)
            viewModel.intentChannel.send(SearchIntent.SearchDiscovery)
        }
    }
private fun loadMore(){
    lifecycleScope.launchWhenCreated {
        viewModel.intentChannel.send(SearchIntent.LoadMoreDiscovery)
    }
}
    override fun initObserver() {
        viewModel.state.observeEvent(this) {
            when (it) {
                is SearchState.HistoryList -> {
                    historyAdapter.submitList(it.list)
                }
                is SearchState.SearchDiscoverList -> {
                    binding.layoutDiscover.visibility = View.VISIBLE
                    discoverAdapter.submitList(it.list)
                }
                is SearchState.SearchHotTopList -> {
                    binding.layoutHot.visibility = View.VISIBLE
                    hotTopAdapter.submitList(it.list)
                }
                is SearchState.SearchHotList -> {
                    hotAdapter.submitList(it.list)
                    if (it.hasMore) {
                        adapterHelper.trailingLoadState = LoadState.NotLoading(false)
                    } else {
                        adapterHelper.trailingLoadState = LoadState.None
                    }
                }
                is SearchState.SearchHotMoreList ->{
                    hotAdapter.addAll(it.list)
                    adapterHelper.trailingLoadState = LoadState.NotLoading(!it.hasMore)
                }
                else -> {}
            }
        }
    }

    override fun initEvent() {
        binding.tvSearch.setOnClickListener(this)
        binding.ivBack.setOnClickListener(this)
        binding.ivDelete.setOnClickListener(this)
        binding.etSearch.setOnKeyListener { v, keyCode, event ->
            if (keyCode == KeyEvent.KEYCODE_ENTER && event?.action == KeyEvent.ACTION_UP) {
                val copy = binding.etSearch.text.toString().trim()
                search(copy)
            }
            false
        }
        historyAdapter.setOnItemClickListener { adapter, _, position ->
            val item = adapter.getItem(position) ?: return@setOnItemClickListener
            launchActivity<SearchResultActivity>(Pair("keyword", item.name))
        }
        discoverAdapter.setOnItemClickListener { adapter, _, position ->
            val item = adapter.getItem(position) ?: return@setOnItemClickListener
            item.term?.let { k->
                search(k)
            }

        }
        hotTopAdapter.setOnItemClickListener { adapter, _, position ->
            val item = adapter.getItem(position) ?: return@setOnItemClickListener
         WebHelper.goodDetails(this,item.spuId)
        }
        hotAdapter.setOnItemClickListener { adapter, _, position ->
            val item = adapter.getItem(position) ?: return@setOnItemClickListener
            WebHelper.goodDetails(this,item.spuId)
        }
    }
    private lateinit var adapterHelper: QuickAdapterHelper
    private fun initView() {
        binding.etSearch.setText(keyword)
        val layoutManager = FlexboxLayoutManager(this)
        layoutManager.flexDirection = FlexDirection.ROW
        layoutManager.justifyContent = JustifyContent.FLEX_START
        binding.rvHistory.layoutManager = layoutManager
        binding.rvHistory.addGridDecoration()
        binding.rvHistory.adapter = historyAdapter
        // 搜索发现
        binding.rvDiscover.layoutManager = GridLayoutManager(this,2)

        binding.rvDiscover.adapter = discoverAdapter
        // 热门搜索顶部
        binding.rvHotTop.layoutManager = GridLayoutManager(this,3)
        binding.rvHotTop.addGridDecoration()
        binding.rvHotTop.adapter = hotTopAdapter
        //
        val loadMoreAdapter = CustomLoadMoreAdapter()
        loadMoreAdapter.setOnLoadMoreListener(this)
        binding.rvHotList.layoutManager = LinearLayoutManager(this)
        binding.rvHotList.addLinearDecoration()
        binding.rvHotList.adapter = hotAdapter
        hotAdapter.animationEnable = true

        hotAdapter.setItemAnimation(BaseQuickAdapter.AnimationType.ScaleIn)
        adapterHelper = QuickAdapterHelper.Builder(hotAdapter)
            .setTrailingLoadStateAdapter(loadMoreAdapter)
            .build()
        binding.rvHotList.adapter = adapterHelper.adapter
    }

    private fun search(keyword: String) {
        lifecycleScope.launchWhenCreated {
            viewModel.intentChannel.send(
                SearchIntent.AddHistory(
                    keyword
                )
            )
            launchActivity<SearchResultActivity>(Pair("keyword", keyword))
            binding.etSearch.setText("")
        }
    }

    override fun onClick(view: View?) {
        when (view?.id) {
            binding.tvSearch.id -> {
                val keyword = binding.etSearch.text.toString().trim()
                search(keyword)
            }
            binding.ivBack.id -> {
                onBackPressed()
            }
            binding.ivDelete.id -> {
                showAlert("删除历史记录？") {
                    lifecycleScope.launchWhenCreated {
                        viewModel.intentChannel.send(SearchIntent.DeleteHistory)
                    }
                }
            }
        }
    }

    override fun onFailRetry() {
        loadMore()
    }

    override fun onLoad() {
        loadMore()
    }
}